from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import mysql.connector, requests, json
from datetime import datetime

app = Flask(__name__)
CORS(app)

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'aichat_user',
    'password': 'qwe13142',
    'database': 'ai_chat',
    'auth_plugin': 'mysql_native_password'
}

# DeepSeek配置
DS_API = "https://api.deepseek.com/v1/chat/completions"
DS_KEY = "sk-2b15bbc494514f79bcee6eaa535d0794"


@app.route('/')
def home():
    return render_template('index.html')


@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    try:
        user_id = data.get('user_id')
        message = data.get('msg')
        if not all([user_id, message]):
            return jsonify(error="缺少必要参数"), 400

        headers = {"Authorization": f"Bearer {DS_KEY}"}
        payload = {
            "model": "deepseek-chat",
            "messages": [{"role": "user", "content": message}]
        }

        res = requests.post(DS_API, headers=headers, json=payload, timeout=10)
        res.raise_for_status()

        reply_data = res.json()
        if 'choices' not in reply_data:
            return jsonify(error="AI服务返回异常"), 500

        reply = reply_data['choices'][0]['message']['content']

        conversation = {
            "user": message,
            "ai": reply
        }
        conversation_json = json.dumps(conversation, ensure_ascii=False)

        with mysql.connector.connect(**db_config) as db:
            cursor = db.cursor()
            cursor.execute(
                "INSERT INTO ai_chat_history (user_id, conversation) VALUES (%s, %s)",
                (user_id, conversation_json)
            )
            db.commit()

        return jsonify(reply=reply)

    except requests.exceptions.RequestException:
        return jsonify(error="AI服务暂不可用"), 503
    except mysql.connector.Error as e:
        return jsonify(error=f"数据保存失败: {str(e)}"), 500
    except Exception:
        return jsonify(error="服务器内部错误"), 500


@app.route('/history')
def history():
    user_id = request.args.get('user_id')
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')

    try:
        def safe_time_convert(t):
            if not t: return None
            try:
                return datetime.fromisoformat(t.replace('T', ' ')).strftime("%Y-%m-%d %H:%M:%S")
            except:
                return None

        start_time = safe_time_convert(start_time)
        end_time = safe_time_convert(end_time)

        with mysql.connector.connect(**db_config) as db:
            cursor = db.cursor(dictionary=True)

            query = "SELECT * FROM ai_chat_history WHERE 1=1"
            params = []

            if user_id:
                query += " AND user_id = %s"
                params.append(user_id)
            if start_time:
                query += " AND create_time >= %s"
                params.append(start_time)
            if end_time:
                query += " AND create_time <= %s"
                params.append(end_time)

            cursor.execute(query, params)

            results = []
            for row in cursor:
                conv = json.loads(row['conversation'])
                results.append({
                    'msg': conv['user'],
                    'reply': conv['ai'],
                    'time': row['create_time'].isoformat()
                })

            return jsonify(results)

    except Exception as e:
        return jsonify(error=f"查询失败：{str(e)}"), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)